"""
Tests for the update() queryset method that allows in-place, multi-object
updates.
"""

from django.db import models
from django.conf import settings

class Product(models.Model):
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=20)
    expires = models.DateTimeField(null=True)

    def __unicode__(self):
        return unicode(self.name)

class RelatedProduct(models.Model):
    name = models.CharField(max_length=20)
    data = models.ForeignKey(Product)

    def __unicode__(self):
        return unicode(self.name)


__test__ = {'API_TESTS': """
>>> from datetime import datetime

>>> Product(name="p0", description="apple").save()
>>> Product(name="p2", description="banana").save()
>>> p3 = Product(name="p3", description="banana")
>>> p3.save()
>>> RelatedProduct(name="r1", data=p3).save()

Objects are updated by first filtering the candidates into a queryset and then
calling the update() method. It executes immediately and returns nothing.

>>> Product.objects.filter(description="apple").update(name="p1")
>>> Product.objects.filter(description="apple")
[<Product: p1>]

We can update multiple objects at once.

>>> Product.objects.filter(description="banana").update(description="pineapple")
>>> Product.objects.get(name="p2").description
u'pineapple'

Foreign key fields can also be updated, although you can only update the object
referred to, not anything inside the related object.

>>> p = Product.objects.get(name="p1")
>>> RelatedProduct.objects.filter(name="r1").update(data=p)
>>> RelatedProduct.objects.filter(data__name="p1")
[<RelatedProduct: r1>]

Multiple fields can be updated at once. If DATABASE_ENGINE is mysql microseconds
must be truncated.

>>> Product.objects.filter(description="pineapple").update(
...     description="fruit",
...     expires=datetime(2010, 1, 1, 12, 0, 0, 123456))
>>> p = Product.objects.get(name="p2")
>>> p.description, p.expires
"""}

if settings.DATABASE_ENGINE == 'mysql':
    __test__['API_TESTS'] += "(u'fruit', datetime.datetime(2010, 1, 1, 12, 0))"
else:
    __test__['API_TESTS'] += "(u'fruit', datetime.datetime(2010, 1, 1, 12, 0, 0, 123456))"

__test__['API_TESTS'] += """

In the rare case you want to update every instance of a model, update() is also
a manager method and update with None works as well.

>>> Product.objects.update(expires=None)
>>> Product.objects.values('expires').distinct()
[{'expires': None}]

We do not support update on already sliced query sets.

>>> DataPoint.objects.all()[:2].update(another_value='another thing')
Traceback (most recent call last):
    ...
AssertionError: Cannot update a query once a slice has been taken.

"""
